package com.cheung.leetcode.str;

import org.junit.jupiter.api.Test;

/**
 * @BelongsProject : java-leetcode
 * @BelongsPackage : com.cheung.leetcode.str
 * @Author :  cheungming
 * @CreateTime : 2024-05-07 08:44:16
 * @Description : 字符串反转
 * @Version : 1.0
 */
public class Code541Test {

    public String reverseStr(String s, int k) {
        char[] array = s.toCharArray();

        // 本题的重点是跳2k格
        for (int i = 0; i < array.length; i += (2 * k)) {
            int start = i;
            // 下标从0开始，所以减1
            int end = Math.min(start + k - 1, array.length - 1);

            // 下面属于交换代码，与主逻辑无关
            while (start < end) {
                array[start] ^= array[end];
                array[end] ^= array[start];
                array[start] ^= array[end];

                start++;
                end--;
            }

        }

        return new String(array);
    }

    @Test
    public void test1() {
        String s = "abcdefg";
        int k = 2;
        String r = "bacdfeg";

        assert r.equals(reverseStr(s, k));
    }

    @Test
    public void test2() {
        String s = "abcd";
        int k = 2;
        String r = "bacd";

        assert r.equals(reverseStr(s, k));
    }
}
